package com.example.administrator.myapplication.chat.adapter;

import android.animation.TypeEvaluator;

import com.alibaba.fastjson.JSON;
import com.example.administrator.myapplication.chat.Print;
import com.example.administrator.myapplication.chat.classstring.ChatRecord;
import com.example.administrator.myapplication.chat.interface_.MessageReceive;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;
import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketFrame;

import org.json.JSONObject;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/11/19.
 */

public class WebAdapter extends WebSocketAdapter {
    private MessageReceive messageReceive;
    public WebAdapter(){}
    public WebAdapter(MessageReceive iin){
        this.messageReceive=iin;
    }

    @Override
    public void onTextMessage(WebSocket websocket, String text) throws Exception {
        super.onTextMessage(websocket, text);
        /*
        * 添加消息判断
        * 消息处理
        * 消息分类
        * 消息分发
        * 1 登录信息返回
        * 2 好友上线
        * 3 收到消息
        * */
        Print.string("收到消息01： "+text.toString());
        JSONObject jsonObject=new JSONObject(text.toString());

        switch (jsonObject.getString("type")){
//        switch ("1"){
            case "1"://登录消息返回
                messageReceive.messageLogin(text);
                break;
            case "2"://好友上线聊天消息返回
                messageReceive.messageFriends(jsonObject.getString("message"));
                break;
            case "3": //好友消息接收 上线下线消息
                messageReceive.message(jsonObject.getString("message"));
                break;
            case "4": //系统发布消息
                messageReceive.messageSystem(jsonObject.getString("message"));
                break;
        }
    }

//    连接成功
    @Override
    public void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception {
        super.onConnected(websocket, headers);
        Print.string("连接成功： "+headers.toString());
    }

//    连接错误
    @Override
    public void onConnectError(WebSocket websocket, WebSocketException exception) throws Exception {
        super.onConnectError(websocket, exception);
        Print.string("连接错误： "+exception.toString());
    }

//    断开连接
    @Override
    public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
        super.onDisconnected(websocket, serverCloseFrame, clientCloseFrame, closedByServer);
        Print.string("断开连接： ");
    }
}
